package cmd

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/alfred_tools/alfred"
	"github.com/spf13/cobra"
)

type bitwardenItem struct {
	Name  string `json:"name"`
	Login struct {
		Username string `json:"username"`
		Password string `json:"password"`
	} `json:"login"`
}

var bitwardenCmd = &cobra.Command{
	Use:   "bitwarden",
	Short: "bitwarden 项目列举",
	Run: func(cmd *cobra.Command, args []string) {
		defer func() {
			wf.SendFeedback()
		}()

		var query string
		if len(args) > 0 {
			query = args[0]
		}

		data, err := wf.Cache.LoadOrStore("bitwarden-items-cache", time.Hour*time.Duration(24), func() ([]byte, error) {
			ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
			defer cancel()
			status, err := alfred.RunCmd(ctx, "bw list items --session xiav2BeUhKyZyin15brEo4lVyOOaxerQFyGux0zAgdQf94i+ENAvMdWJhfuU7wBe0Z1VJbxTQOLrWIdVo677zA==")
			if err != nil || status.Exit != 0 {
				log.Printf("status:%+v err:%+v", status, err)
				return nil, errors.New("查询密码项出错")
			}
			info := strings.Join(status.Stdout, "")
			return []byte(info), nil
		})

		if err != nil {
			wf.Fatal("查询密码项出错")
			return
		}

		var items []bitwardenItem
		json.Unmarshal(data, &items)

		log.Printf("items:%+v", items)

		if len(items) == 0 {
			wf.Fatal("未找到密码项")
			return
		}

		for _, v := range items {
			if !strings.Contains(v.Name, query) && !strings.Contains(v.Login.Username, query) {
				continue
			}
			item := wf.NewItem(v.Name).Valid(true).
				Subtitle(v.Login.Username).
				Arg(v.Login.Password)
			item.Ctrl().Subtitle("复制用户名").Arg(v.Login.Username).Valid(true)

			item.Cmd().Arg(fmt.Sprintf("%s|%s", v.Login.Username, v.Login.Password)).
				Subtitle("快捷登录").
				Var("quick", "true").
				Valid(true)
		}
	},
}
